package com.haochang.chunkvod.controller.fragment.hostess;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.config.ServerErrorCodeConfig;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.ScreenUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.view.vod.ViewGroup.CustomFlowLayout;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.dialog.ActivityDialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.ChooseActivityDialog;
import com.haochang.chunkvod.view.vod.dialog.DialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.KeyBoardDialog;
import com.haochang.chunkvod.view.vod.dialog.SingleSelectionDialog;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

/**
 *         created at 2016/8/25 16:27
 *         房间管理-空房页面
 */
public class RoomNoneFragment extends BaseFragment implements KeyBoardDialog.KeyBoardOnSureListener, CustomFlowLayout.OnSingleCheckedChangeListener_
{
	//房间用途选择文本
	private CustomFlowLayout flowLayout;
	//人数，备注输入框
	private BaseEditText et_count, et_desc;
	// 选择活动
	private BaseTextView room_choice_activity;
	// 权限验证
	private BaseTextView room_grant;
	//是否已通过权限验证
	private boolean hasAuthorized = false;
	//授权是否成功小icon及右箭头隐藏
	private ImageView iv_granted_success, iv_arrow_right;
	//权限验证下方的文本,需要根据是否验证改变字体颜色
	private BaseTextView tv_room_none_time, tv_room_none_h, tv_room_none_m, tv_room_fees, room_fees, tv_room_room_type, room_room_type;
	//接受点击的横栏
	private LinearLayout group_room_fees, group_room_room_type;
	// 预结时间输入框
	private BaseEditText room_pre_h, room_pre_m;
	// 大客户复选框
	private CheckBox checkBox_big_customer;
	//确定按钮
	private Button room_ok;
	//当前选择的功能编号,默认为唱歌
	private int current_UsageCode = 0;
	//当前被点击的输入框
	private BaseEditText current_et;
	//当前计费方式
	private String currentFees = "0";
	//当前计费房型
	private String roomType = "";
	private String roomId = "";
	private String roomTypeId = "";
	//当前选择活动
	private String currentActivity = "";
	private ArrayList<ActivityDialogItemInfo> listChooseActivity = new ArrayList<ActivityDialogItemInfo>();//活动
	private HostessData hostessData;
	private String authCode = "";//权鉴的code
	private String reservationTime;//预结时间
	private long lastTimeFromNet;//最近一次服务器时间
	private long lastTimeLocal;//最近一次本地时间
	private ArrayList<DialogItemInfo> listUsage = new ArrayList<DialogItemInfo>();//房间用途list
	private ArrayList<DialogItemInfo> listRoomPolicies = new ArrayList<DialogItemInfo>();//房间计费策略list
	private ArrayList<DialogItemInfo> listRoomTypes = new ArrayList<DialogItemInfo>();//房间类型list
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
	private SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_room_none, container,false);
		hostessData = new HostessData((BaseActivity) getActivity());
		initView(view);

		return view;
	}

	private void initView(View view)
	{
		LinearLayout group_room_choice_activity = (LinearLayout) view.findViewById(R.id.group_room_choice_activity);
		LinearLayout group_room_grant = (LinearLayout) view.findViewById(R.id.group_room_grant);
		flowLayout = (CustomFlowLayout) view.findViewById(R.id.flowLayout);
		iv_arrow_right = (ImageView) view.findViewById(R.id.iv_arrow_right);
		iv_granted_success = (ImageView) view.findViewById(R.id.iv_granted_success);

		et_count = (BaseEditText) view.findViewById(R.id.et_count);
		et_desc = (BaseEditText) view.findViewById(R.id.et_desc);
		room_choice_activity = (BaseTextView) view.findViewById(R.id.room_choice_activity);
		room_grant = (BaseTextView) view.findViewById(R.id.room_grant);
		tv_room_none_time = (BaseTextView) view.findViewById(R.id.tv_room_none_time);
		tv_room_none_h = (BaseTextView) view.findViewById(R.id.tv_room_none_h);
		tv_room_none_m = (BaseTextView) view.findViewById(R.id.tv_room_none_m);
		tv_room_fees = (BaseTextView) view.findViewById(R.id.tv_room_fees);
		room_fees = (BaseTextView) view.findViewById(R.id.room_fees);
		tv_room_room_type = (BaseTextView) view.findViewById(R.id.tv_room_room_type);
		room_room_type = (BaseTextView) view.findViewById(R.id.room_room_type);
		room_pre_h = (BaseEditText) view.findViewById(R.id.room_pre_h);
		room_pre_m = (BaseEditText) view.findViewById(R.id.room_pre_m);
		checkBox_big_customer = (CheckBox) view.findViewById(R.id.checkBox_big_customer);
		room_ok = (Button) view.findViewById(R.id.room_ok);
		group_room_fees = (LinearLayout) view.findViewById(R.id.group_room_fees);
		group_room_room_type = (LinearLayout) view.findViewById(R.id.group_room_room_type);

		room_fees.setCompoundDrawablePadding(DipPxConversion.dipToPx(getActivity(), 4));
		room_room_type.setCompoundDrawablePadding(DipPxConversion.dipToPx(getActivity(), 4));

		et_count.setOnClickListener(etClickListener);
		room_pre_h.setOnClickListener(etClickListener);
		room_pre_m.setOnClickListener(etClickListener);
		et_count.setOnClickListener(etClickListener);
		et_count.addTextChangedListener(watcher);
		room_pre_h.addTextChangedListener(watcher);
		room_pre_m.addTextChangedListener(watcher);

		group_room_choice_activity.setOnClickListener(mOnBaseClickListener);
		group_room_grant.setOnClickListener(mOnBaseClickListener);
		room_grant.setOnClickListener(mOnBaseClickListener);
		group_room_fees.setOnClickListener(mOnBaseClickListener);
		group_room_room_type.setOnClickListener(mOnBaseClickListener);
		room_ok.setOnClickListener(mOnBaseClickListener);
		flowLayout.setOnSingleCheckedChangeListener_(this);

		hasAuthorized=true;
		refreshAuthorizationView();
		initIntentData();
	}

	/**
	 * 获取初始化数据
	 */
	private void initIntentData()
	{
		roomType = getArguments().getString(IntentKey.ROOM_TYPE);
		roomId = getArguments().getString(IntentKey.ROOM_ID);
		roomTypeId = getArguments().getString(IntentKey.ROOM_TYPE_ID);
		listChooseActivity = getArguments().getParcelableArrayList(IntentKey.ACTIVITY_LIST);
		listRoomPolicies = getArguments().getParcelableArrayList(IntentKey.ROOM_POLICIES);
		listRoomTypes = getArguments().getParcelableArrayList(IntentKey.ROOM_TYPES);
		String customer_count = getArguments().getString(IntentKey.ROOM_DEFAULT_COUNT);//房间默认人数
		// 房间用途
		listUsage = getArguments().getParcelableArrayList(IntentKey.USAGE_LIST);
		room_room_type.setText(roomType);
		//计费方式
		if (listRoomPolicies.size() > 0)
		{
			room_fees.setText(listRoomPolicies.get(0).getName());
			listRoomPolicies.get(0).setSelected(true);
		}
		if (!TextUtils.isEmpty(customer_count))
		{
			et_count.setText(customer_count);
		}
		//显示用途列表
		initRoomUsage(listUsage);
		requestReservationTime();
	}

	/**
	 * 请求预结时间
	 */
	private void requestReservationTime()
	{
		hostessData.requestMostStatementTime(roomTypeId, "", new HostessData.StatementTimeListener()
		{
			@Override
			public void onRequestSuccess(String time, long serverTime)
			{
				if (!TextUtils.isEmpty(time))
				{
					lastTimeFromNet = serverTime * 1000;//毫秒
					lastTimeLocal = System.currentTimeMillis();
					reservationTime = time;
					String[] strs = TimeUtils.getMinutesString(time).split(":");
					if (strs.length == 2)
					{
						room_pre_h.setText(strs[0]);
						room_pre_m.setText(strs[1]);
					}
				}

			}

			@Override
			public void onFail(int errno, String errMsg)
			{

			}
		});
	}

	private boolean hadAdded2;//是否已添加房间用途

	/**
	 * 房间用途
	 *
	 * @param listUsage 名称列表
	 */
	private void initRoomUsage(ArrayList<DialogItemInfo> listUsage)
	{
		if (listUsage != null && listUsage.size() > 0)
		{
			if (flowLayout.getChildCount() <= 0)
			{
				int length = listUsage.size();
				View[] views = new View[length];
				if (length > 0 && !hadAdded2)
				{
					int width = ScreenUtils.getScreenWidth(getContext()) / 5;
					int wrapDp = DipPxConversion.dip2px(getContext(), 70);
					int _20dp = DipPxConversion.dip2px(getContext(), 20);
					for (int j = 0; j < length; j++)
					{
						DialogItemInfo itemInfo = listUsage.get(j);
						if (itemInfo == null)
						{
							continue;
						}
						LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(wrapDp, LinearLayout.LayoutParams.MATCH_PARENT);
						final ViewGroup viewGroup = null;
						RadioButton radioButton = (RadioButton) LayoutInflater.from(getContext()).inflate(R.layout.inflate_flowlayot_usage, viewGroup, false);
						params.setMargins((width - wrapDp) / 2, 0, (width - wrapDp) / 2, _20dp);
						radioButton.setLayoutParams(params);
						radioButton.setText(itemInfo.getName());
						if (j == 0)
						{
							radioButton.setChecked(true);
						} else
						{
							radioButton.setChecked(false);
						}
						views[j] = radioButton;
					}
					flowLayout.addData(views, true);
					hadAdded2 = true;
				}
			}
		}
	}

	private TextWatcher watcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			String countStr = et_count.getText().toString().trim();
			if (!TextUtils.isEmpty(countStr) && Integer.parseInt(countStr) > 1000)
			{
				ToastUtils.showText(getActivity(), "房间人数超过1000，请重新输入!");
				et_count.setText("");
				et_count.requestFocus();
			}
			if (Integer.parseInt(room_pre_h.getText().toString().trim()) > 23)
			{
				room_pre_h.setText(String.valueOf("23"));
			}
			if (Integer.parseInt(room_pre_m.getText().toString().trim()) > 59)
			{
				room_pre_m.setText(String.valueOf("59"));
			}
			DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();
			decimalFormat.applyPattern("00");
			String time = "";
			long currenTimeFromNet = lastTimeFromNet + (System.currentTimeMillis() - lastTimeLocal);//点击时计算服务器当前时间
			try
			{
				time = simpleDateFormatDay.format(simpleDateFormat.parse(reservationTime)) + " "
						+ decimalFormat.format(Long.parseLong(room_pre_h.getText().toString())) + ":"
						+ decimalFormat.format(Long.parseLong(room_pre_m.getText().toString())) + ":00";
			} catch (Exception e)
			{
				Logger.e(e.getMessage());
			}
			Logger.e("time:" + time + "  " + currenTimeFromNet);
			try
			{
				Logger.e("设定:" + (simpleDateFormat.parse(time).getTime() - currenTimeFromNet));
				if ((simpleDateFormat.parse(time).getTime() - currenTimeFromNet <= 30 * 60 * 1000))
				{
					room_ok.setClickable(false);
					room_ok.setEnabled(false);
					room_ok.setBackgroundResource(R.drawable.shape_gray);
					ToastUtils.showText(getContext(), String.format(Locale.getDefault(), "预结时间离当前时间已不足%d分钟", 30));
				} else
				{
					room_ok.setClickable(true);
					room_ok.setEnabled(true);
					room_ok.setBackgroundResource(R.drawable.dialog_sure_btn);
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}

		@Override
		public void afterTextChanged(Editable s)
		{

		}
	};

	/**
	 * 数字输入框点击事件监听
	 */
	private OnBaseClickListener etClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			if (v.getId() == R.id.group_et_count)
			{
				current_et = et_count;
			} else
			{
				current_et = (BaseEditText) v;
			}
			KeyBoardDialog keyBoardDialog = new KeyBoardDialog(getActivity());
			keyBoardDialog.setKeyBoardOnSureListener(RoomNoneFragment.this);
			keyBoardDialog.show();
		}
	};

	/**
	 * 点击事件监听
	 */
	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{

		@Override
		public void onBaseClick(View v)
		{
			Intent intent;
			switch (v.getId())
			{
			case R.id.group_room_grant:
				//权限验证
				intent = new Intent(getActivity(), AuthorizationDialogActivity.class);
				intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.HOSTESS_GRANT_OPEN);
				startActivityForResult(intent, IntentCode.HOSTESS_GRANT_REQUEST);
				break;
			case R.id.group_room_choice_activity:
				//选择活动
				if (CollectionUtils.isEmpty(listChooseActivity))
				{
					ToastUtils.showText(getActivity(), "该房型暂无活动");
					return;
				}
				new ChooseActivityDialog.Builder(getActivity()).setTitle("选择活动")
						.setSingleChoiceItems(listChooseActivity, new ChooseActivityDialog.OnSingleChoosedListner()
						{
							@Override
							public void onSingleChoosed(ActivityDialogItemInfo info)
							{
								room_choice_activity.setText(info.getName());
								currentActivity = info.getId();
							}
						}).createDialog(8).show();
				break;
			case R.id.group_room_fees:
				//选择计费方式
				new SingleSelectionDialog.Builder(getActivity()).setTitle("计费方式")
						.setSingleChoiceItems(listRoomPolicies, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								room_fees.setText(name);
								currentFees = code;
								room_fees.setCompoundDrawablePadding(DipPxConversion.dipToPx(getActivity(), 4));
							}
						}).createDialog(5).show();
				break;
			case R.id.group_room_room_type:
				for (int i = 0; i < listRoomTypes.size(); i++)
				{
					if (listRoomTypes.get(i).getCode().equals(roomTypeId))
					{
						listRoomTypes.get(i).setSelected(true);
					} else
					{
						listRoomTypes.get(i).setSelected(false);
					}
				}
				new SingleSelectionDialog.Builder(getActivity()).setTitle("计费房型")
						.setSingleChoiceItems(listRoomTypes, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								room_room_type.setText(name);
								roomType = name;
								roomTypeId = code;
								room_room_type.setCompoundDrawablePadding(DipPxConversion.dipToPx(getActivity(), 4));
							}
						}).createDialog(5).show();
				break;
			case R.id.room_ok:
				//点击ok按钮 提交数据
				commit();
				break;
			}
		}
	};

	/**
	 * 提交开房请求
	 */
	private void commit()
	{
		if (isLegal())
		{
			DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();
			decimalFormat.applyPattern("00");
			String time = "";
			try
			{
				time = simpleDateFormatDay.format(simpleDateFormat.parse(reservationTime)) + " "
						+ decimalFormat.format(Long.parseLong(room_pre_h.getText().toString())) + ":"
						+ decimalFormat.format(Long.parseLong(room_pre_m.getText().toString())) + ":00";
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			Logger.e("time:" + time);
			String remarks = TextUtils.isEmpty(et_desc.getText().toString().trim()) ? "" : et_desc.getText().toString().trim();
			hostessData.requestCreateBill(roomId, et_count.getText().toString(), currentActivity, listUsage.get(current_UsageCode).getCode(), currentFees, time,
					roomTypeId, remarks, checkBox_big_customer.isChecked() ? 1 : 0, authCode, new HostessData.NoticeListener()
					{
						@Override
						public void onRequestSuccess(String notice)
						{
							if (!TextUtils.isEmpty(notice))
							{
								ToastUtils.showText(getActivity(), "开房成功");
								getActivity().setResult(Activity.RESULT_OK);
								getActivity().finish();
							}
						}

						@Override
						public void onFail(int errorNo, String errorMsg)
						{
							if (errorNo == ServerErrorCodeConfig.TIMES_ERROR)
							{
								//预结时间错误
								//requestEndTime(currentRoomTypeDesign);
								if (TextUtils.isEmpty(reservationTime))
								{// 从网络获取预结时间
									requestReservationTime();
								} else
								{
									//将预结时间恢复到默认
									resumeReservationTime();
								}
							} else if (errorNo == ServerErrorCodeConfig.AUTHORIZATION_ERROR)
							{
								//这个是授权码错误
								//先将预结时间恢复到默认
								resumeReservationTime();
								resumeRoomPolicies();
								//重新授权
								hasAuthorized = false;
								authCode = "";
								refreshAuthorizationView();
								ToastUtils.showText(getContext(), TextUtils.isEmpty(errorMsg) ? "权限验证失败!" : errorMsg);
							}
						}
					});
		}
	}

	/**
	 * 恢复默认的预结时间
	 */
	private void resumeReservationTime()
	{
		SimpleDateFormat simpleDateFormatHH = new SimpleDateFormat("HH", Locale.getDefault());
		SimpleDateFormat simpleDateFormatmm = new SimpleDateFormat("mm", Locale.getDefault());
		try
		{
			room_pre_h.setText(simpleDateFormatHH.format(simpleDateFormat.parse(reservationTime)));
			room_pre_m.setText(simpleDateFormatmm.format(simpleDateFormat.parse(reservationTime)));
		} catch (Exception e)
		{
			room_pre_h.setText(String.valueOf("0"));
			room_pre_m.setText(String.valueOf("0"));
		}
	}

	/**
	 * 恢复默认 房间计费策略//计费方式
	 */
	private void resumeRoomPolicies()
	//房间计费策略
	{
		room_fees.setText(listRoomPolicies.get(0).getName());
		currentFees = "0";
		roomType = getArguments().getString(IntentKey.ROOM_TYPE);
		roomTypeId = getArguments().getString(IntentKey.ROOM_TYPE_ID);
		room_room_type.setText(roomType);
	}

	/**
	 * 判断输入合法性
	 * @return 输入结果是否合法
	 */
	private boolean isLegal()
	{
		if (TextUtils.isEmpty(et_count.getText().toString()))
		{
			ToastUtils.showText(getContext(), "请输入人数");
			return false;
		} else if (listUsage == null || listUsage.size() <= 0)
		{
			ToastUtils.showText(getActivity(), "未获取房间用途信息");
			return false;
		}
		return true;
	}

	@Override
	public void setValue(String value)
	{
		try
		{
			if (value.contains("."))
				ToastUtils.showText(getActivity(), R.string.error_number);
			else if (Integer.parseInt(value) <= 0)
				ToastUtils.showText(getActivity(), R.string.error_number);
			else
			{
				current_et.setText(value);
			}
		} catch (Exception e)
		{
			ToastUtils.showText(getActivity(), getResources().getString(R.string.error_max_number));
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.HOSTESS_GRANT_REQUEST && resultCode == FragmentActivity.RESULT_OK && data != null)
		{
			authCode = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			if (!TextUtils.isEmpty(authCode))
			{
				hasAuthorized = true;
				refreshAuthorizationView();
			} else
			{
				ToastUtils.showText(getActivity(), "用户名或密码错误");
			}
		}
	}

	/**
	 * 根据权限是否验证通过显示下方的内容
	 */
	private void refreshAuthorizationView()
	{
		int color;
		int colorTv;
		if (hasAuthorized)
		{
			color = this.getResources().getColor(R.color.color_282828);
			colorTv = this.getResources().getColor(R.color.color_737373);
			room_pre_h.setEnabled(true);
			room_pre_m.setEnabled(true);
			group_room_fees.setEnabled(true);
			group_room_room_type.setEnabled(true);
			iv_granted_success.setImageResource(R.drawable.ic_success);
			room_grant.setText("已通过");
			room_grant.setTextColor(getResources().getColor(R.color.color_4bbb4d));
			iv_arrow_right.setVisibility(View.GONE);
		} else
		{
			color = this.getResources().getColor(R.color.color_a9a9a9);
			colorTv = this.getResources().getColor(R.color.color_a9a9a9);
			room_pre_h.setEnabled(false);
			room_pre_m.setEnabled(false);
			group_room_fees.setEnabled(false);
			group_room_room_type.setEnabled(false);
			iv_granted_success.setImageResource(R.drawable.ic_warn);
			room_grant.setText("未通过");
			room_grant.setTextColor(getResources().getColor(R.color.color_ffab40));
			iv_arrow_right.setVisibility(View.VISIBLE);

		}
		tv_room_none_time.setTextColor(color);
		room_pre_h.setTextColor(color);
		tv_room_none_h.setTextColor(colorTv);
		room_pre_m.setTextColor(color);
		tv_room_none_m.setTextColor(colorTv);
		tv_room_fees.setTextColor(color);
		room_fees.setTextColor(colorTv);
		tv_room_room_type.setTextColor(color);
		room_room_type.setTextColor(colorTv);
	}

	@Override
	public void onSingleCheckedChanged_(int position, boolean b, CompoundButton compoundButton)
	{
		current_UsageCode = position;
	}
}
